package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 检查项服务
 */

@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {
    @Autowired
    private CheckItemDao checkItemDao;

    @Override
    public void add(CheckItem checkItem) {

        checkItemDao.add(checkItem);
    }

    @Override
    //检查项分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //mybatis分页助手完成分页查询操作
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckItem> page = checkItemDao.selectByCondition(queryString);
        //借助上面的分页助手获取总页数和查询到的checkItem的list集合
        long total = page.getTotal();
        List<CheckItem> result = page.getResult();

        //有参构造一个新的pageResult集合，封入上面查到的total和list
        return new PageResult(total,result);
    }

    @Override
    //删除检查项
    public void delete(Integer id) {
       long count = checkItemDao.findCountByCheckItemId(id);
       if (count > 0){
           throw new RuntimeException("当前检查项被其他表引用，无法删除");
       }
       checkItemDao.deleteById(id);
    }

    @Override
    //编辑检查项
    public void edit(CheckItem checkItem) {
        checkItemDao.edit(checkItem);
    }

    @Override
    //根据id查询检查项
    public CheckItem findById(Integer id) {
        return checkItemDao.findById(id);
    }

    //查询所有检测项
    @Override
    public List<CheckItem> findAll() {
        return checkItemDao.findAll();
    }
}
